<script setup>
import { ref, watch, onMounted } from 'vue'
// import { createBlobUrl } from '@renderer/utils'

const _props = defineProps({
  file: {
    type: Object,
    default: () => {}
  }
})

const src = ref('')
const type = ref('audio/mpeg')
const voiceLength = ref(0)
const audioPlay = ref(null) // 音频播放器
const isPlaying = ref(false) // 是否正在播放

watch(
  () => _props.file,
  (newVal) => {
    type.value = newVal._mediaType
    // src.value = createBlobUrl(newVal.buffer, newVal._mediaType)
    const { filePath } = newVal
    src.value = filePath
    voiceLength.value = (newVal._metadata.voiceLength / 1000).toFixed(2)
  },
  { immediate: true }
)
// 播放
const play = () => {
  stopOtherAudio(audioPlay.value)
  audioPlay.value.play()
  isPlaying.value = true
}
// 停止
const stop = () => {
  audioPlay.value.pause()
  audioPlay.value.currentTime = 0 // 将音频的当前时间设置为0，即回到开始位置
  isPlaying.value = false
}

// 播放或者暂停
const togglePlay = () => {
  if (audioPlay.value.paused) {
    play()
  } else {
    stop()
  }
}

// 播放 一个 audio 其它的都暂停
function stopOtherAudio(audio) {
  const audios = document.querySelectorAll('audio')
  audios.forEach((item) => {
    if (item !== audio) {
      item.pause()
      item.currentTime = 0
    }
  })
}

onMounted(() => {
  audioPlay.value.addEventListener('ended', stop)
  audioPlay.value.addEventListener('pause', stop)
})
</script>

<template>
  <div class="overflow-hidden">
    <audio ref="audioPlay" class="hidden" :src="src" controls></audio>
    <div @click="togglePlay">
      <el-button
        type="primary"
        class="bg-transparent border-none"
        style="color: var(--el-text-color-regular)"
        :loading="isPlaying"
        :disabled="false"
      >
        <div>
          <el-icon v-show="!isPlaying" class="mx-0.5"><Microphone /></el-icon>
          <el-text size="small" class="mx-2">{{ voiceLength }}s</el-text>
        </div>
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
